package com.gmt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author John.zhang
 * @version Id: AuthRoutePredicateFactory, v 1.0 2020/11/20 15:11 ZhiYong Exp $
 * 后缀必须是RoutePredicateFactory
 */
@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {

    Logger logger = LoggerFactory.getLogger(AuthRoutePredicateFactory.class);

    public AuthRoutePredicateFactory() {
        super(Config.class);
    }

    public static final String NAME_KEY = "name";

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME_KEY);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        logger.info("AuthRoutePredicateFactory.apply");
        return exchange -> {
            HttpHeaders headers = exchange.getRequest().getHeaders();
            //header是否有Authorization
            List<String> headerList = headers.get(config.getName());
            return headerList != null && headerList.size() > 0;
        };
    }

    public static class Config {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
